package com.mths.client.content;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.FlowPanel;
import com.mths.client.component.Anchor;
import com.mths.client.controller.LoginMenuController;
import com.mths.client.controller.LoginMenuControllerAsync;
import com.mths.client.dto.AuthDataDTO;
import com.mths.client.util.AsyncCall;
import com.mths.client.util.ClientCacheUtil;
import com.mths.client.util.MenuItem;
import com.mths.client.util.PageUtil;

public class MenuManager extends FlowPanel {

	private final LoginMenuControllerAsync menuService = GWT.create(LoginMenuController.class);

	@Override
	protected void onLoad() {
		super.onLoad();
		String openPageFriendlyUrl = PageUtil.getUrlPageToken();
		refreshMenuAndPrivilege(openPageFriendlyUrl);
	}

	public void refreshMenuAndPrivilege(final String openPageFriendlyUrl) {
		menuService.loadMenuItemsAndPrivileges("", new AsyncCall<AuthDataDTO>() {
			@Override
			public void successCall(AuthDataDTO authData) {
				ClientCacheUtil.instance().loginProcess(authData, openPageFriendlyUrl);
				// loadMenu(authData.getMenuItemList(), openPageFriendlyUrl);
			}

		});
	}

	public void loadMenu(List<MenuItem> result, String openPageFriendlyUrl) {
		clear();
		for (MenuItem menuItem : result) {
			if (menuItem.getVisible()) {
				Anchor testMenu = new Anchor();
				testMenu.setHref("#".concat(menuItem.getFriendlyUrl()));
				testMenu.setText(menuItem.getName());
				testMenu.addStyleName("nav-header");
				add(testMenu);
			}
		}
		if (openPageFriendlyUrl == null || openPageFriendlyUrl.isEmpty()) {
			goFisrtMenu();
		} else {
			PageUtil.navigationManager.controlOpenPageByFUrl(openPageFriendlyUrl);
		}
	}

	private void goFisrtMenu() {
		if (ClientCacheUtil.instance().getClientMenuList() != null && !ClientCacheUtil.instance().getClientMenuList().isEmpty()) {
			PageUtil.navigationManager.controlOpenPageByFUrl(ClientCacheUtil.instance().firstVisibleMenuFUrl());
		}
	}

}
